package com.exp.base.freemaker;

import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import com.exp.base.freemaker.ResourceVersionManager;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

//@Component("scriptDirective")
public class ScriptDirective implements TemplateDirectiveModel {
	@Resource
	ResourceVersionManager resourceVersionManager;
	
	@Override
	public void execute(Environment env, Map map, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		StringBuilder scriptSb = new StringBuilder();
		scriptSb.append("<script ");
		for(Object key : map.keySet()){
			if("src".equals(key)){
				String value = map.get(key).toString();
				String version = resourceVersionManager.getMd5(value);
				scriptSb.append(" ").append(key).append("=\"").append(value).append("?version=").append(version).append("\" ");
			}else{
				scriptSb.append(" ").append(key).append("=\"").append(map.get(key)).append("\" ");
			}
		}
		scriptSb.append(" />\r\n");
		String scriptStr = scriptSb.toString();
		env.getOut().write(scriptStr);
		System.out.println(scriptStr);

	}

}
